import React, { useState, useEffect, useCallback } from 'react';
import { Modal, Input, Table, Space, Button, message, App as AntdApp, Tag } from 'antd';
import { SearchOutlined, UserOutlined } from '@ant-design/icons';
import type { User } from '@/api/system';
import { getUserSimpleList, getRoleUsers, assignRoleUsers } from '@/api/system';
import { useQuery } from '@tanstack/react-query';

const { Search } = Input;

interface UserAssignDialogProps {
  visible: boolean;
  roleId: string | number;
  roleName: string;
  onClose: () => void;
  onSuccess?: () => void;
}

const UserAssignDialog: React.FC<UserAssignDialogProps> = ({
  visible,
  roleId,
  roleName,
  onClose,
  onSuccess,
}) => {
  const { modal } = AntdApp.useApp();
  const [searchUsername, setSearchUsername] = useState('');
  const [searchName, setSearchName] = useState('');
  const [selectedUsers, setSelectedUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);

  // 获取所有用户列表
  const { data: allUsers, refetch: refetchUsers } = useQuery({
    queryKey: ['user-simple-list', searchUsername, searchName],
    queryFn: async () => {
      const response = await getUserSimpleList({
        username: searchUsername,
        name: searchName,
      });
      return response;
    },
    enabled: visible,
  });

  // 获取当前角色的用户列表
  const { data: roleUsers, refetch: refetchRoleUsers } = useQuery({
    queryKey: ['role-users', roleId],
    queryFn: async () => {
      const response = await getRoleUsers(roleId);
      return response;
    },
    enabled: visible,
  });

  // 初始化选中状态
  useEffect(() => {
    if (roleUsers && allUsers) {
      const roleUserIds = roleUsers.map(user => user.id);
      const selected = allUsers.filter(user => roleUserIds.includes(user.id));
      setSelectedUsers(selected);
    }
  }, [roleUsers, allUsers]);

  // 处理搜索
  const handleSearch = useCallback(() => {
    refetchUsers();
  }, [refetchUsers]);

  // 处理行选择
  const handleRowSelect = (selectedRowKeys: React.Key[], selectedRows: User[]) => {
    setSelectedUsers(selectedRows);
  };

  // 处理分配用户
  const handleAssignUsers = async () => {
    if (selectedUsers.length === 0) {
      message.warning('请至少选择一个用户');
      return;
    }

    setLoading(true);
    try {
      await assignRoleUsers(roleId, selectedUsers.map(user => user.id));
      message.success('用户分配成功');
      onSuccess?.();
      onClose();
    } catch (error) {
      message.error('用户分配失败');
    } finally {
      setLoading(false);
    }
  };

  // 表格列定义
  const columns = [
    {
      key: 'username',
      title: '用户名',
      dataIndex: 'username',
      width: 200,
      render: (text: string) => (
        <Space>
          <UserOutlined />
          {text}
        </Space>
      ),
    },
    {
      key: 'name',
      title: '姓名',
      dataIndex: 'name',
      width: 150,
      render: (text: string) => text || '-',
    },
  ];

  const rowSelection = {
    selectedRowKeys: selectedUsers.map(user => user.id),
    onChange: handleRowSelect,
    type: 'checkbox' as const,
  };

  return (
    <Modal
      title={`分配用户 - ${roleName}`}
      open={visible}
      onCancel={onClose}
      width={900}
      onOk={handleAssignUsers}
      confirmLoading={loading}
      destroyOnClose
    >
      <div style={{ marginBottom: 16 }}>
        <Space size="middle">
          <Search
            placeholder="搜索用户名"
            value={searchUsername}
            onChange={(e) => setSearchUsername(e.target.value)}
            onSearch={handleSearch}
            style={{ width: 200 }}
            allowClear
          />
          <Search
            placeholder="搜索姓名"
            value={searchName}
            onChange={(e) => setSearchName(e.target.value)}
            onSearch={handleSearch}
            style={{ width: 200 }}
            allowClear
          />
          <Button icon={<SearchOutlined />} onClick={handleSearch}>
            搜索
          </Button>
        </Space>
      </div>

      <Table
        columns={columns}
        dataSource={allUsers || []}
        rowKey="id"
        rowSelection={rowSelection}
        pagination={false}
        scroll={{ y: 400 }}
        size="middle"
        loading={!allUsers}
      />
    </Modal>
  );
};

export default UserAssignDialog;